from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from community.models import Label, Article, Comment
# SerializerMethodField 可以自定义字段  字段数据来自方法返回
from rest_framework.fields import SerializerMethodField


# 标签序列化器
class LabelSerializer(ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'


# 文章序列化器
class ArticleSerializer(ModelSerializer):
    # 展示用户的头像 和用户的名字  Article 模型
    # 关联查询
    user_name = serializers.CharField(source="user.username", read_only=True)
    user_avatar = serializers.CharField(source="user.userdetail.avatar", read_only=True)

    class Meta:
        model = Article
        exclude = ["is_delete"]
        extra_kwargs = {
            "page_view": {"read_only": True},
            "priority": {"read_only": True},
        }


# 评论的序列化器
class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source="user.username", read_only=True)
    user_avatar = serializers.CharField(source="user.userdetail.avatar", read_only=True)
    # 新的方法  字段数据来自于查询统计得到的
    # 方法名  就是字段名
    son_comment_count = SerializerMethodField(read_only=True)

    class Meta:
        model = Comment
        exclude = ["is_delete"]

    def get_son_comment_count(self, comment):
        # 得到parent_comment的所有数据  也就是得到子级评论的数量
        return comment.parent_comment_set.count()


# 新增一个展示子级评论的序列化器
class SonCommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source="user.username", read_only=True)
    user_avatar = serializers.CharField(source="user.userdetail.avatar", read_only=True)
    reply_username = serializers.CharField(source="reply_comment.user.username", read_only=True)

    class Meta:
        model = Comment
        exclude = ["is_delete"]
